//
//  WBOAthViewController.swift
//  WB
//
//  Created by macssss on 16/7/4.
//  Copyright © 2016年 macssss. All rights reserved.
//

import UIKit
import SVProgressHUD

//MARK: - 设置新浪登录界面
class WBOAthViewController: UIViewController {

    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white()
        
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充密码", target: self, action: #selector(autoFill))
        
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        guard let url = URL(string : urlString) else {
            
            return
        }
        
        let request = URLRequest(url : url)
        
        webView.loadRequest(request)
        
    }

    //MARK: - 实现登录界面发回方法
    @objc private func close() {
        
        SVProgressHUD.dismiss()
        
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func  autoFill() {
        
        // 准备 js
        let js = "document.getElementById('userId').value = '641140586@qq.com'; " +
        "document.getElementById('passwd').value = '608836';"

        
        
//        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn'; " +
//        "document.getElementById('passwd').value = 'pqzm123$';"

        

        
        webView.stringByEvaluatingJavaScript(from: js)
    }
    

}

//MARK: -  webView代理方放——————
extension WBOAthViewController: UIWebViewDelegate {
    
    //webView 将要加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("加载请求\(request.url?.absoluteString)")
        if request.url?.absoluteString?.hasPrefix(WBRedirectURI) == false {
            
            return true
         }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            
            close()
            return false
            
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        
        
        print("授权码 \(code)")
        WBNetworkManager.shared.loadAccessToken(code: code) {(isSuccess) in
            
            if !isSuccess {
                
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                
               
                
                //发送通知
                NotificationCenter.default.post(name: Notification.Name(rawValue: WBUserLoginSuccessedNotification), object: nil)
                
                self.close()
            }
            
        }
        
        return false
    }
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
        //下一步 跳转界面 
    }
    
}









